package edu.ynu.MyProject.controller;

import edu.ynu.MyProject.common.controller.LogicController;
import edu.ynu.MyProject.dao.IDataDao;
import edu.ynu.MyProject.dto.WeatherDTO;
import edu.ynu.MyProject.entity.Data;
import edu.ynu.MyProject.service.DataService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@Api(tags = "数据")
@RestController
@RequestMapping("/data")
public class DataController extends LogicController<DataService, IDataDao, Data, Long> {
    public DataController(@Autowired DataService service) {
        super(service);
    }

    @GetMapping("/allValues/{greenhouseId}")
    public ResponseEntity<Map<String,Object>> getDataByGreenhouseId(@PathVariable Long greenhouseId) throws IOException {
        service.refreshData(greenhouseId);
        Map<String,Object> allDataDTO =service.getAllDataDTO(greenhouseId);
        return ResponseEntity.ok(allDataDTO);
    }

    @GetMapping("/image/capture/{greenhouseId}")
    public String getCaptureByGreenhouseId(@PathVariable Long greenhouseId) throws IOException {
        return service.saveImages(greenhouseId);
    }

    @GetMapping("/temperatures/{greenhouseId}")
    public WeatherDTO getTemperatureLineChart(@PathVariable Long greenhouseId) throws IOException {
        return service.getTemperatureDTO(greenhouseId);
    }

    @GetMapping("/image/get/{greenhouseId}")
    public ResponseEntity<Resource> getImageByGreenhouseId(@PathVariable Long greenhouseId){
        File file = service.getImage(greenhouseId);

        if (file == null){
            return ResponseEntity.notFound().build();
        }
        Resource resource = new FileSystemResource(file);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName())
                .contentType(MediaType.IMAGE_PNG)
                .body(resource);
    }
}
